package com.zy.chat.controller;

import cn.hutool.core.util.StrUtil;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import static com.zy.chat.constants.constants.*;
import java.io.File;
import java.io.IOException;
import java.util.UUID;

/**
 * @author zy
 * @date 2023/6/4 22:34
 */

@Controller
@RequestMapping(value = "upload")
public class uploadController {

    @PostMapping(value = "file")
    public ResponseEntity<String> upload(@RequestParam("file")MultipartFile file){

        String fileName=file.getOriginalFilename();
        String newFileName=createNewFileName(fileName);
        try {
         file.transferTo(new File(IMAGE_UPLOAD_DIR,newFileName));
        return new ResponseEntity<String>(newFileName, HttpStatus.OK);
        } catch (IOException e) {
            throw new RuntimeException("文件上传失败",e);
        }

    }

    private String createNewFileName(String originalFilename) {
        // 获取后缀
        String suffix = StrUtil.subAfter(originalFilename, ".", true);
        // 生成目录
        String name = UUID.randomUUID().toString();
        int hash = name.hashCode();
        int d1 = hash & 0xF;
        int d2 = (hash >> 4) & 0xF;
        // 判断目录是否存在
        File dir = new File(IMAGE_UPLOAD_DIR, StrUtil.format("/dyimgs/{}/{}", d1, d2));
        if (!dir.exists()) {
            dir.mkdirs();
        }
        // 生成文件名
        return StrUtil.format("/dyimgs/{}/{}/{}.{}", d1, d2, name, suffix);
    }
}
